import dbfread
import openpyxl
import os
import re
from multiprocessing import Process

root_in_path = "E:\\毕设数据\\QuNDVI_DBF\\"
root_out_path = "E:\\毕设数据\\QuNDVI_Excel\\"

dbf_demo = r"C:\Users\91481\Desktop\毕业设计\demo\20000201MOD13A3A2000032h27v050062015138123527_wuhan.dbf"


# dbf = dbfread.DBF(filename=dbf_demo, load=True)


class Converter(object):
    def __init__(self, dbf_file):
        self.dbf = dbfread.DBF(dbf_file, load=True)
        self.value_data = []
        self.value_count = []

    @property
    def data(self):
        for i in self.dbf:
            if i["Value"] >= 0:
                self.value_data.append(i["Value"] / 10000)
            else:
                self.value_data.append(0)
            self.value_count.append(i["COUNT"])
        self.value_min = min(self.value_data)
        self.value_max = max(self.value_data)
        self.value_mean = sum(self.value_data) / sum(self.value_count)
        return (self.value_data, self.value_count)

    @property
    def max(self):
        return self.value_max

    @property
    def min(self):
        return self.value_min

    @property
    def mean(self):
        return self.value_mean

    def save(self, filename):
        data = self.data
        if not filename.endswith(".xlsx") or filename.endswith(".xls"):
            raise ValueError(f"filename {filename} invalid!, please give an valid excel file name")
        workbk = openpyxl.workbook.Workbook()
        workst = workbk.active
        workst.cell(1, 1, "Value")
        workst.cell(1, 2, "Count")
        workst.cell(1, 3, "Max")
        workst.cell(2, 3, self.max)
        workst.cell(1, 4, "Min")
        workst.cell(2, 4, self.min)
        workst.cell(1, 5, "Mean")
        workst.cell(2, 5, self.mean)
        for i in range(len(data[0])):
            workst.cell(i + 2, 1, data[0][i])
            workst.cell(i + 2, 2, data[1][i])
        workbk.save(filename)

        return


def file_filter(folder):
    """返回一个文件夹中所有dbf文件绝对路径"""
    files = []
    r_files = os.listdir(folder)

    for i in r_files:
        if i.endswith(".dbf"):
            files.append(os.path.join(folder, i))
    return files


def do_qu_dbf(qu_dir, root_out_path):
    in_folders = []
    for x in os.listdir(qu_dir):
        if os.path.isdir(os.path.join(qu_dir, x)):
            in_folders.append(os.path.join(qu_dir, x))

    for i in in_folders:
        # print(i)
        out_path = os.path.join(os.path.join(root_out_path, os.path.basename(qu_dir)), "Excel_" + i[-4:])
        if not os.path.exists(out_path):
            os.makedirs(out_path)

        dbf = file_filter(i)

        for d in dbf:
            # print(d)
            cvr = Converter(d)
            out_file_name = re.search(".*\\\(.*)\.dbf", d).group(1)
            save_name = os.path.join(out_path, out_file_name + ".xlsx")
            if os.path.exists(save_name):
                print(save_name + " exist !")
                continue
            else:
                cvr.save(save_name)
                print(save_name + " OK !")


def do_dbf(in_dir, out_dir):
    # print(i)
    out_path = os.path.join(out_dir, "Excel_" + in_dir[-4:])
    if not os.path.exists(out_path):
        os.makedirs(out_path)
    #     print(out_path)
    dbf = file_filter(in_dir)

    for d in dbf:
        print(d)
        cvr = Converter(d)
        out_file_name = re.search(".*\\\(.*)\.dbf", d).group(1)
        save_name = os.path.join(out_path, out_file_name + ".xlsx")
        if os.path.exists(save_name):
            print(save_name + " exist !")
            continue
        else:
            cvr.save(save_name)
            print(save_name + " OK !")


def run():
    qu = os.listdir(root_in_path)
    plist = []
    for q in qu:
        arg = os.path.join(root_in_path, q)
        print(arg)
        p = Process(target=do_qu_dbf, args=(arg,))
        plist.append(p)
    for i in plist:
        i.start()


if __name__ == "__main__":
    # do_qu_dbf("E:\\毕设数据\\QuNDVI_DBF\\江夏区")
    # ins = "E:\\毕设数据\\UsingTypeNDVI_DBF\\"
    # outs = "E:\\毕设数据\\UsingTypeNDVI_Excel"
    # ins = "E:\\毕设数据\\VegetationTypeNDVI_DBF\\"
    # outs = "E:\\毕设数据\\VegetationTypeNDVI_Excel"
    ins = "E:\\毕设数据\\WuhanNDVI_DBF\\"
    outs = "E:\\毕设数据\\WuhanNDVI_Excel"
    qu = os.listdir(ins)
    for q in qu:
        print(os.path.join(ins, q))
        do_dbf(os.path.join(ins, q), outs)

